package com.sky.controller.user;


import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.sky.constant.StatusConstant;
import com.sky.entity.Dish;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.utils.RedisUtil;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

import static com.sky.constant.RedisConstant.DISH_CACHE;

@RestController("userDishController")
@RequestMapping("/user/dish")
@Slf4j
@Api(tags = "C端-菜品浏览接口")
public class DishController {
    @Autowired
    private DishService dishService;

    @Resource
    private RedisUtil redisUtil;

    /**
     * 根据分类id查询菜品
     *
     * @param categoryId
     * @return
     */
    @GetMapping("/list")
    @ApiOperation("根据分类id查询菜品")
    public Result<List<DishVO>> list(Long categoryId) {
        long start = System.currentTimeMillis();
        //查询缓存
        String key = DISH_CACHE + categoryId;
        String Json = (String) redisUtil.get(key);
        // 解析 JSON 字符串
        List<DishVO> dishes = JSON.parseObject(Json, new TypeReference<List<DishVO>>() {});
        if (dishes != null){
            System.out.println("Redis查询菜品时间：{}"+ (System.currentTimeMillis() - start) + "毫秒");
            return Result.success(dishes);

        }
        Dish dish = new Dish();
        dish.setCategoryId(categoryId);
        dish.setStatus(StatusConstant.ENABLE);//查询起售中的菜品

        List<DishVO> list = dishService.listWithFlavor(dish);
        String jsonString = JSON.toJSONString(list);
        redisUtil.set(key,jsonString);
        System.out.println("数据库查询菜品时间：{}"+ (System.currentTimeMillis() - start)+"毫秒");
        return Result.success(list);
    }

}
